package cn.hl.hm.handler;

import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.constants.WeixinPayConfig;
import cn.hl.hm.dao.TRechargeActivityMapper;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.RechargeRecoard;
import cn.hl.hm.entity.TRechargeActivity;
import cn.hl.hm.entity.UnifiedOrderRequest;
import cn.hl.hm.entity.UnifiedOrderRespose;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.service.PushToAppIService;
import cn.hl.hm.service.RechargeRecoardService;
import cn.hl.hm.util.NumberUtils;
import cn.hl.hm.util.SignWX;
import cn.hl.hm.util.WXUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.vizhuo.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import smsClient.TestSDKClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 微信APP支付handler
 * 
 * @author 大和
 *
 */
@Service
public class WxRecPayHandler extends PayHandler {

	private static final Logger logger = Logger.getLogger(WxRecPayHandler.class);
	@Autowired
	@Qualifier("weixinpayRoadRec")
	private WeixinPayConfig weixinpayRoadRec;
	@Autowired
	@Qualifier("weixinpayRoadQYBRec")
	private WeixinPayConfig weixinpayRoadQYBRec;
	
	
	@Autowired
	RechargeRecoardService rechargeRecoardService;
	@Autowired
	DriverService driverService;

	@Autowired
	@Qualifier("pushToAppServiceImpl")
	private PushToAppIService pushToAppIService;
	
	@Autowired
	TRechargeActivityMapper tRechargeActivityMapper;
	/**
	 * 处理微信支付请求
	 */
	@Override
	public Map<String, String> handler(Map<String, String> payMap) {
		String orderCode = payMap.get("rechargeCode");
		String iosFlag = payMap.get("iosFlag");

		HashMap<String, String> map = new HashMap<String, String>();
		

		// 支付参数
		String nonceStr = SignWX.create_nonce_str();
		String ip = WXUtil.getLocalNetWorkIp();
		String seconds = WXUtil.getTimeStamp();
		UnifiedOrderRequest uor = new UnifiedOrderRequest();
		// 01 找订单 TODO
		RechargeRecoard orderParam = new RechargeRecoard();
		orderParam.setRechargeCode(orderCode);
		List<RechargeRecoard> selectOrder = rechargeRecoardService.selectRechargeRecoard(orderParam);
		RechargeRecoard order = null;
		if(selectOrder!=null&&selectOrder.size()>0){
			order = selectOrder.get(0);
		}else {
			return map;
		}

		Integer rechargeActivityId = order.getRechargeActivityId();
		if(rechargeActivityId==null) {
			uor.setTotal_fee(NumberUtils.y2f(order.getAmount() + "") + "");

		}else {
			TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeActivityId);
			if(tRechargeActivity==null){
				return map;
			}	
			uor.setTotal_fee(NumberUtils.y2f(tRechargeActivity.getAmount() + "") + "");

		}
		
		WeixinPayConfig config = weixinpayRoadRec;

		if(iosFlag.equals("1")){
			config = weixinpayRoadQYBRec;
		}
		logger.info(".....[配置参数]："+config.toString());

		// UnifiedOrderRequest 赋值 TODO 共计10个参数
		uor.setSpbill_create_ip(ip);
		uor.setBody("叮当到干线物流-余额充值");// APP叮当到微信支付
		uor.setNonce_str(nonceStr);
		uor.setAppid(config.getAppId());
		uor.setMch_id(config.getMchId());
		uor.setNotify_url(config.getNotifyUrl());
		uor.setOut_trade_no(order.getRechargeCode());
		uor.setTrade_type("APP");
		uor.setKey(config.getKey());
		String sign = WXUtil.createSign(uor);
		uor.setSign(sign);
		uor.setKey(null);
		// 将订单对象转为xml格式
		XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_"))); // <span
																							// style="color:#ff0000;"><strong>说明3(见文末)</strong></span>
		xStream.alias("xml", UnifiedOrderRequest.class);// 根元素名需要是xml
		String orderXml = xStream.toXML(uor);
		logger.info("...........微信支付：" + orderXml);
		// 生成订单XML
		String resultMap = WXUtil.httpOrder(orderXml);
		if (resultMap != null && !("null".equals(resultMap))) {
			String paySign = null;
			UnifiedOrderRequest a = new UnifiedOrderRequest();

			a.setAppid(config.getAppId());// 微信开放平台审核通过的应用APPID
			a.setMch_id(config.getMchId());// 微信支付分配的商户号
			a.setNonce_str(nonceStr);// 随机字符串
			a.setTimestamp(seconds);
			a.setPrepay_id(resultMap);
			a.setKey(config.getKey());
			paySign = WXUtil.createSignTwo(a);
			map.put("appid", config.getAppId());
			map.put("noncestr", nonceStr);
			map.put("package", "Sign=WXPay");
			// map.put("package", "prepay_id=" + resultMap);
			map.put("partnerid", config.getMchId());
			map.put("prepayid", resultMap);
			map.put("timestamp", seconds);

			map.put("sign", paySign);
			return map;
		} else {
			return null;
		}
	}

	@Override
	protected void initHandler() {
		register(PayMethod.ROAD_WX_RECHARGE, WxRecPayHandler.class);
	}

	/**
	 * 回调请求
	 */
	@Override
	public Boolean callback(HttpServletRequest request, HttpServletResponse response) {
		try {
			BufferedReader reader = request.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			logger.info("----[微信回调]接收到的报文---" + inputString.toString());
			XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));// 说明3(见文末)
			xStream.alias("xml", UnifiedOrderRespose.class);
			UnifiedOrderRespose unifiedOrderRespose = (UnifiedOrderRespose) xStream.fromXML(inputString.toString());
			
			
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("appid", unifiedOrderRespose.getAppid()); // 微信开放平台审核通过的应用APPID
			parameters.put("attach", unifiedOrderRespose.getAttach()); // 商家数据包
			parameters.put("bank_type", unifiedOrderRespose.getBank_type()); // 微信支付分配的商户号
			parameters.put("cash_fee", unifiedOrderRespose.getCash_fee()); // 现金支付金额
			parameters.put("fee_type", unifiedOrderRespose.getFee_type()); // 货币种类
			parameters.put("is_subscribe", unifiedOrderRespose.getIs_subscribe());// 是否关注公众账号
			parameters.put("mch_id", unifiedOrderRespose.getMch_id()); // 商户号
			parameters.put("nonce_str", unifiedOrderRespose.getNonce_str());
			parameters.put("openid", unifiedOrderRespose.getOpenid());// 用户标识
			parameters.put("out_trade_no", unifiedOrderRespose.getOut_trade_no()); // 商户订单号
			parameters.put("result_code", unifiedOrderRespose.getResult_code()); // 业务结果
			// parameters.put("return_code",
			// unifiedOrderRespose.getReturn_code());
			parameters.put("time_end", unifiedOrderRespose.getTime_end()); // 支付完成时间
			parameters.put("total_fee", unifiedOrderRespose.getTotal_fee()); // 总金额
			parameters.put("trade_type", unifiedOrderRespose.getTrade_type()); // 交易类型APP
			parameters.put("transaction_id", unifiedOrderRespose.getTransaction_id()); // 微信支付订单号
			// 反校验签名
			String sign = null; 

			
			
			
			logger.info("开始进入支付成功方法里：");
			if (null != unifiedOrderRespose && "SUCCESS".equals(unifiedOrderRespose.getReturn_code())) {
				logger.info("已经进入支付成功方法里------：unifiedOrderRespose"+unifiedOrderRespose.toString());
				if (StringUtils.isBlank(unifiedOrderRespose.getOut_trade_no())) {
					return false;
				}
				return processBusiness(unifiedOrderRespose);
			} else {
				return false;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;

		}

	}

	private Boolean processBusiness(UnifiedOrderRespose unifiedOrderRespose) {
		// 查订单
		RechargeRecoard orderParam = new RechargeRecoard();
		orderParam.setRechargeCode(unifiedOrderRespose.getOut_trade_no());
		List<RechargeRecoard> selectOrder = rechargeRecoardService.selectRechargeRecoard(orderParam);
		RechargeRecoard order = null;
		if(selectOrder!=null&&selectOrder.size()>0){
		
		}else {
			return false;
		}
		if (selectOrder != null && selectOrder.size() > 0) {
			order = selectOrder.get(0);
			logger.info("......回调排查信息：  订单 "+order.toString());
			if (StringUtils.isBlank(unifiedOrderRespose.getSign())) {// 签名为空
				return false;
			}
			
			String orderStatus = order.getStatus();
			if (orderStatus.equals("1")) {
				String userPaymentTime = unifiedOrderRespose.getTime_end();// 支付时间
				logger.info("......支付时间" + userPaymentTime);
				if (userPaymentTime != null && !("null".equals(userPaymentTime))) {
				} else {
					userPaymentTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				}
				Date string2Date = DateUtil.string2Date(userPaymentTime, "yyyyMMddHHmmss");
				logger.info("......转换后支付时间" + string2Date);
				// 1 修改订单
				return updateOrder(order, string2Date);
			} else {
				return true;
			}

		} else {
			return false;
		}
	}
	
	private Boolean updateOrder(RechargeRecoard order, Date string2Date) {
		// 1 修改订单
		RechargeRecoard orderParam2 = new RechargeRecoard();
		orderParam2.setUpdateTime(string2Date);
		orderParam2.setStatus("2");
		orderParam2.setId(order.getId());
		orderParam2.setType(1);

		int updateRechargeRecoard = rechargeRecoardService.updateRechargeRecoard(orderParam2);
		if(updateRechargeRecoard>0){
			//driver money
			Driver driver = new Driver();
			driver.setRemainCash(order.getRemainCash());
			driver.setId(order.getDriverId());
			
			int res = driverService.updateDriver(driver);
				if(res>0){
					//发短信
					TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(order.getRechargeActivityId());
					if(tRechargeActivity!=null){
						if(order.getUserphone()!=null){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
							String format = sdf.format(new Date());
							//TestSDKClient.testSendSMSE(order.getUserphone(), "【华凌叮当到】温馨提示您，您的账户于"+format+"通过微信充值"+tRechargeActivity.getAmount()+"元，活动奖励"+tRechargeActivity.getGiftAmount()+"元，账户余额"+order.getRemainCash()+"元【华凌叮当到：400-998-3903】");
							  try {
							SendSmsRequest smsRequest = new SendSmsRequest();
							smsRequest.setTemplateParam("{\"rechargeAmount\":\""+tRechargeActivity.getAmount()+"\",\"giftAmount\":\""+tRechargeActivity.getGiftAmount()+"\",\"remainCash\":\""+order.getRemainCash()+"\",\"currentDate\":\""+format+"\"}");
							TestSDKClient.sendSmsByAli("SMS_110495052",smsRequest,order.getUserphone(),"华凌叮当到");
						} catch (Exception e) {
								e.printStackTrace();
							}

							
						}
						
					}else {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
						String format = sdf.format(new Date());
						SendSmsRequest smsRequest = new SendSmsRequest();
						smsRequest.setTemplateParam("{\"rechargeAmount\":\""+order.getAmount()+"\",\"remainCash\":\""+order.getRemainCash()+"\",\"currentDate\":\""+format+"\"}");
						TestSDKClient.sendSmsByAli("SMS_112470204",smsRequest,order.getUserphone(),"华凌叮当到");
					}
					return true;
				}else {
					return false;
				}
		}else {
			return false;
		}
	}

}
